package com.cta.service.report;

import java.util.Date;
import java.util.List;

import com.cta.constant.ReportTypeConst;
import com.cta.entity.MasterData;
import com.cta.view.model.report.EntityParams;

public class ReportSqlBuilder {

	public static String buildSql(List<MasterData> tables, ReportTypeConst type, EntityParams entity, Date fromDate,
			Date toDate) {
		if (tables == null || tables.size() <= 0) {
			return null;
		}
		StringBuilder bf = new StringBuilder();
		for (int i = 0; i < tables.size(); i++) {
			MasterData table = tables.get(i);
			bf.append(getSelect(table.getTableName(), type)).append(getCondition(entity, fromDate, toDate))
					.append(getGroupBy(type)).append(getOrderBy());
			if (i < tables.size() - 1) {
				bf.append(" union ");
			}
		}
		return bf.toString();
	}

	private static String getSelect(String table, ReportTypeConst type) {
		if (ReportTypeConst.BillingSummaryReport == type) {
			return "select count(*), def_telco as telCo from " + table;
		}
		return "select * from " + table;
	}

	private static String getCondition(EntityParams entity, Date fromDate, Date toDate) {
		StringBuilder bf = new StringBuilder(" where ");
		if ("contact".equals(entity.getType())) {
			String in = "";
			for (int i = 0; i < entity.getIds().size(); i++) {
				in += entity.getIds();
				if (i < entity.getIds().size() - 1) {
					in += ", ";
				}
			}
			bf.append(String.format(" def_user_id in ( %s ) ", in));
		}

		if (fromDate != null & toDate != null) {
			bf.append(" and ?<= def_start_date <= ?");
		}
		return bf.toString();
	}

	private static String getGroupBy(ReportTypeConst type) {
		if (ReportTypeConst.BillingSummaryReport == type) {
			return " group by def_telco";
		}
		return "";
	}

	private static String getOrderBy() {
		return " order by count";
	}

}
